package com.lst.projectlib.component.GridView;

import com.lst.projectlib.util.DensityUtil;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewParent;
import android.widget.ScrollView;

public class DragGridViewForScrollView extends DragGridView {
	private int minScrollDistance = 0;
	
	public DragGridViewForScrollView(Context context) {
        super(context);
        
        init(context);
    }

    public DragGridViewForScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        
        init(context);
    }

    public DragGridViewForScrollView(Context context, AttributeSet attrs,
        int defStyle) {
        super(context, attrs, defStyle);
        
        init(context);
    }
    
    private void init(Context context) {
    	minScrollDistance = DensityUtil.dip2px(context, 80);
    }
        
    @Override
    /**
     * 重写该方法，达到使ListView适应ScrollView的效果
     */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
        MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
    	ViewParent parent = getParent();
    	while (parent != null) {
    		if (parent instanceof ViewPager || parent instanceof ScrollView) {
    			parent.requestDisallowInterceptTouchEvent(isDrag);
    		}
    		parent = parent.getParent();
		}
    	
    	return super.onTouchEvent(ev);
    }
    
    @Override
    protected void autoScroll() {
    	// 如果GridView在ScrollView中，则滚动事件需要处理ScrollView的
		boolean isInScrollView = false;
		ViewParent parent = getParent();
    	while (parent != null) {
    		if (parent instanceof ScrollView) {
    			isInScrollView = true;
    			break;
    		}
    		parent = parent.getParent();
		}
    	if (isInScrollView && parent instanceof ScrollView) {
			ScrollView pView = (ScrollView) parent;

			int dY = 0;
			float scrollY = pView.getScrollY();
			float y = getY();
			
			int moveYToTop = (int)(moveY + y - scrollY);
			int moveYToBottom = pView.getHeight() - moveYToTop;
			
			if (moveYToBottom < minScrollDistance && scrollY <= (y + getHeight() - pView.getHeight())) {
				dY = speed;
				mHandler.postDelayed(mScrollRunnable, 25);
			} else if (moveYToTop < minScrollDistance && y <= scrollY) {
				dY = -speed;
				mHandler.postDelayed(mScrollRunnable, 25);
			} else {
				dY = 0;
				mHandler.removeCallbacks(mScrollRunnable);
			}

			pView.smoothScrollBy(0, dY);
    	} else {
    		super.autoScroll();
    	}
    }
}
